/*
*===============DdmgCloudPlatform3 V2.0===============
* DdmgCloudPlatform3 V2.0
* Copyright@大大买钢2018,All Rights Reserved
* Author: yiChangBin(2055960489@qq.com)
* Date: 2019/6/6  9:15
* TODO: 销售-->销售合同页面
*===============DdmgCloudPlatform3 V2.0===============
*/
<template>
    <d2-container class="trade-order-page" v-if="initInfo">
        <template slot="header">
            <div class="flex header">
                <span class="title">销售合同{{titleStatus}}</span>
                <span class="flex-1"/>
                <span class="cherck_name">操作员：{{initInfo.updater || loginInfo.name}}</span>
                <span class="order_no">合同单号：{{initInfo.order_no || "保存后生成"}}</span>
            </div>
            <el-form :model="initInfo" ref="ruleFormOne" :rules="ruleQueryOne" class="order-content">
                <el-row :gutter="10">
                    <table-search-option-cell
                            :span="6"
                            label="登记机构："
                            label-width="100px"
                            prop="institutional_id"
                            :dataList="institutionalTree"
                            v-model="initInfo.institutional_id"
                            @change="onInstitutionalChange"
                    />
                    <table-search-option-cell
                            :span="6"
                            label="部门："
                            label-width="100px"
                            prop="department_id"
                            :dataList="departmentList"
                            v-model="initInfo.department_id"
                            @change="onDepartmentChange"
                    />
                    <table-search-option-cell
                            :span="6"
                            label="业务员："
                            label-width="100px"
                            prop="clerk_id"
                            :dataList="employeeList"
                            v-model="initInfo.clerk_id"
                    />
                    <el-col :span="6">
                        <el-form-item label="签订日期：" label-width="100px" prop="order_date">
                            <el-date-picker
                                    :clearable="false"
                                    v-model="initInfo.order_date"
                                    type="date"
                                    placeholder="选择日期" format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%;"
                                    :picker-options="beforTodayOption"
                                    :disabled="initInfo.isUpdDel>1"
                            />
                        </el-form-item>
                    </el-col>

                    <table-search-input-cell
                            :span="6"
                            label="合同编号："
                            label-width="100px"
                            prop="agreement_no"
                            v-model="initInfo.agreement_no"
                            placeholder="请输入合同编号"
                            :disabled="initInfo.isUpdDel>1"
                    />

<!--                    <el-col :span="6">
                        <el-form-item label="有效期：" label-width="100px" prop="order_date">
                            <el-date-picker
                                    :clearable="false"
                                    v-model="initInfo.order_date"
                                    type="date"
                                    placeholder="选择日期" format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%;"
                                    :picker-options="beforTodayOption"
                                    :disabled="initInfo.isUpdDel>1"
                            />
                        </el-form-item>
                    </el-col>-->
                    <el-col :span="6">
                        <el-form-item label="有效期：" label-width="100px" prop="arrivedDate">
                            <el-date-picker
                                    :clearable="false"
                                    @change="onDateChange"
                                    :picker-options="{shortcuts: pickerOptionsOne}"
                                    unlink-panels
                                    v-model="initInfo.arrivedDate"
                                    type="daterange"
                                    range-separator="~"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :default-time="['00:00:00', '23:59:59']"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                    class="JHDatePicker"
                                    :disabled="isUpdDel>1"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="购货单位：" label-width="100px" prop="buy_unit_id">
                            <el-ajax-select
                                    transCode="E3000007"
                                    :data="betweenUnitTree"
                                    :propQuery="{
                                        name: uintPropName
                                    }"
                                    v-model="initInfo.buy_unit_id"
                                    @change="onBetweenUnitChange"
                                    :disabled="isUpdDel>1 || saleType===1"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="项目：" label-width="100px" prop="second_unit_id">
                            <el-ajax-select
                                    ref="projectUnitRef"
                                    transCode="E3000008"
                                    :data="projectUnitList"
                                    :propQuery="{
                                        name: projectPropName,
                                        id: initInfo.buy_unit_id
                                    }"
                                    v-model="initInfo.second_unit_id"
                                    :disabled="isUpdDel>1 || !initInfo.buy_unit_id  || saleType===1"
                            />
                        </el-form-item>
                    </el-col>


                    <table-search-input-cell
                            :span="6"
                            label="供货重量："
                            label-width="100px"
                            prop="weight"
                            v-model="initInfo.weight"
                            placeholder="请输入供货重量"
                            @keyup.native="resetValue(initInfo, 'weight')"
                            :disabled="initInfo.isUpdDel>1"
                    />

                    <table-search-input-cell
                            :span="6"
                            label="合同金额："
                            label-width="100px"
                            prop="amount"
                            v-model="initInfo.amount"
                            placeholder="请输入合同金额"
                            @keyup.native="resetValue(initInfo, 'amount')"
                            :disabled="initInfo.isUpdDel>1"
                    />

                    <table-search-input-cell
                            :span="6"
                            label="备注："
                            label-width="100px"
                            v-model="initInfo.remark"
                            placeholder="请输入备注"
                            :disabled="initInfo.isUpdDel>1"
                    />
                </el-row>
            </el-form>
        </template>
        <div class="flex detail"><span class="title">物资明细</span></div>
        <sales-contract-item-table ref="editItemTable" :type="type"></sales-contract-item-table>

        <div class="flex detail" style="margin-top: 10px" ><span class="title">合同条款</span></div>
        <div class="components-container">
            <div>
                <tinymce v-model="initInfo.comment" :height="300" :isLook="false"/>
            </div>
        </div>

        <template slot="footer">
            <div class="flex fonter-container">
                <span class="flex-1"/>
                <span class="errorMsg" v-if="initInfo.isUpdDel>1">{{initInfo.errorMessage}}</span>
                <el-button size="mini" @click="close">关闭</el-button>
                <el-button :disabled="initInfo.isUpdDel>1 || initInfo.items.length ===0" type="primary"
                           size="mini" @click="onSaveSelf" :loading="saveLoading">保存
                </el-button>
            </div>
        </template>
    </d2-container>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import { createNamespacedHelpers } from "vuex";
  import { mapGetters } from "vuex";
  import datePickerOptions from "@/utils/datePickerOptions";
  import { RULES } from "@/utils/validate";
  import tableSearchOptionCell from "@/components/UI/tableSearchOptionCell";
  import tableSearchInputCell from "@/components/UI/tableSearchInputCell";
  import { add, subtract, multiply, divide } from "@/utils/mathematics";
  import ElAjaxSelect from "@/components/UI/ElAjaxSelect";
  import { throttle } from "lodash";
  import salesContractItemTable from "./salesContractItemTable";
  const { mapState, mapActions, mapMutations } = createNamespacedHelpers("ddmg/salesContractOperation");
  import { resetInputQuantity, resetInputWeight, resetInputMoney } from "@/utils";

  export default {
    name: "salesContractEdit",
    components: {
      tableSearchOptionCell,
      tableSearchInputCell,
      salesContractItemTable,
      ElAjaxSelect,
      Tinymce,
    },
    props: {
      titleStatus: {
        type: String,
        default() {
          return "";
        },
      },
      type: {
        type: Number | String,
        default() {
          return "";
        },
      },
    },

    data() {
      return {
        ruleQueryOne: RULES.salesContractItemEditRuleOne,
        isCotalWeight: false,
        isCostInit: false,
        saveLoading: false,
        stateType: "edit",
        beforTodayOption: datePickerOptions.beforTodayOption,
      };
    },

    methods: {
      ...mapActions(["setInstitutionalChangeEvent", "setDepartmentChangeEvent", "setEmployeeChangeEvent", "addSalesContract", "modifySalesContract", "supplyBetweenUnitEvent"]),
      ...mapMutations([]),

      resetFields() {
        this.$nextTick(() => {
          if (this.$refs["ruleFormOne"]) this.$refs["ruleFormOne"].resetFields();
          if (this.$refs["editItemTable"]) this.$refs["editItemTable"].resetFields();
        });
      },

      resetValue(item, valueType) {
        if (valueType === "amount") {
          item[valueType] = resetInputMoney(item[valueType]);
        } else if (valueType === "weight") {
          item[valueType] = resetInputWeight(this, item[valueType]);
        }
      },

      // 供货单位方式变化
      supplyBetweenUnitChange(value) {
        this.supplyBetweenUnitEvent(value);
      },

      onInstitutionalChange(id) {
        //机构发生改变, 部门变化, 业务员和仓库取业务单元和部门合集去重
        this.initInfo.department_id = "";
        this.initInfo.clerk_id = "";
        if (id) {
          this.setInstitutionalChangeEvent(id);
        }

        this.$nextTick(() => {
          this.$refs["ruleFormOne"].clearValidate();
        });
      },

      onDepartmentChange(id) {
        this.initInfo.clerk_id = "";
        if (id) {
          this.setDepartmentChangeEvent(id);
        }
        this.$nextTick(() => {
          this.$refs["ruleFormOne"].clearValidate();
        });
      },

      onEmployeeChange(id) {
        //业务员发生改变
        if (id) {
          this.setEmployeeChangeEvent(id);
        }
        this.$nextTick(() => {
          this.$refs["ruleFormOne"].clearValidate();
        });
      },

      onBetweenUnitChange({ value }) {
        if (value) {
          setTimeout(() => {
            this.$refs.projectUnitRef.defaultSelect(this.initInfo.buy_unit_id).then((result) => {
              let data = result.data.data || [];
              let firstItem = data[0];
              if (firstItem) {
                this.initInfo.second_unit_id = firstItem.id;
                this.$refs.projectUnitRef.listQuery.name = firstItem.name;
              }
            });
          }, 10);
        } else {
          this.initInfo.second_unit_id = "";
          this.$refs.projectUnitRef.listQuery.name = "";
        }
        this.$nextTick(() => {
          this.$refs["ruleFormOne"].clearValidate();
        });
      },

      validateFormOne() {
        return new Promise((resolve, reject) => {
          this.$refs["ruleFormOne"].validate((valid) => {
            if (valid) resolve();
            else this.$message.error("部分必填字段不符合要求!");
          });
        });
      },

      //新单或者编辑保存
      onSaveSelf: throttle(function() {
        const formOne = new Promise((resolve, reject) => {
          this.$refs["ruleFormOne"].validate((valid) => {
            if (valid) resolve();
            else this.$message.error("部分必填字段不符合要求!");
          });
        });
        const formTable = this.$refs["editItemTable"].validateForm();
        Promise.all([formOne, formTable]).then(() => {
          this.saveLoading = true;
          const reqSucess = (res) => {
            this.$store.dispatch("ddmg/salesContract/getDataList"); //刷新现货入库单列表
            this.$parent.getInitInfo({ type: 3, order_no: res.data });
            this.saveLoading = false;
          };
          const reqFail = (e) => {
            this.saveLoading = false;
            console.error(e);
          };
          if (this.type == 1) {
            //新增
            this.addSalesContract()
            .then(reqSucess)
            .catch(reqFail);
          } else {
            //编辑
            this.modifySalesContract()
            .then(reqSucess)
            .catch(reqFail);
          }
        });
      }, 1000),

      close() {
        this.$store.dispatch("d2admin/page/close", {
          tagName: "/sale/salesContractOperation",
          vm: this,
        });
      },
    },
    computed: {
      // 购货单位name
      uintPropName() {
        let item,
          value = "";
        if (this.initInfo.buy_unit_id && this.betweenUnitTree.length > 0) {
          item = this.betweenUnitTree.filter((obj) => obj.id == this.initInfo.buy_unit_id);
          value = item[0] ? item[0].name : "";
        }
        return value;
      },

      // 项目name
      projectPropName() {
        let item,
          value = "";
        if (this.initInfo.second_unit_id && this.projectUnitList.length > 0) {
          item = this.projectUnitList.filter((obj) => obj.id == this.initInfo.second_unit_id);
          value = item[0] ? item[0].name : "";
        }
        return value;
      },
      ...mapState({
        initInfo: (state) => state.editInitInfo,
        institutionalTree: (state) => state.institutionalTree,
        betweenUnitTree: (state) => state.betweenUnitTree,
        projectUnitList: (state) => state.projectUnitList,
        departmentList: (state) => state.departmentList,
        employeeList: (state) => state.employeeList,
      }),
      ...mapGetters(["loginInfo"]),
      isDisabled() {
        return !!this.initInfo.isUpdDel && this.initInfo.isUpdDel != 1 && this.stateType == "edit";
      },
    },
  };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    @import "../../../../assets/style/tradeOrderPage1";
</style>
<style rel="stylesheet/scss" lang="scss">
    .JHDatePicker {
        i,
        span {
            line-height: 14px !important;
        }
        input {
            font-size: 12px !important;
        }
    }
</style>
